package cn.loioi.distribution.cfg;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.InitializingBean;

import cn.loioi.distribution.db.DbManger;

public class DistributionCfgManage implements InitializingBean {
	private DbManger dbManger;
	private final Map<String, Object> properties = new HashMap<>();

	public void setDbManger(DbManger dbManger) {
		this.dbManger = dbManger;
	}

	public String getString(String key, String defaultValue) {
		return MapUtils.getString(properties, key, defaultValue);
	}

	public Boolean getBoolean(String key, Boolean defaultValue) {
		return MapUtils.getBoolean(properties, key, defaultValue);
	}

	public Integer getInteger(String key, Integer defaultValue) {
		return MapUtils.getInteger(properties, key, defaultValue);
	}

	public Float getFloat(String key, Float defaultValue) {
		return MapUtils.getFloat(properties, key, defaultValue);
	}

	public Object put(String key, Object value) {
		return properties.put(key, value);
	}

	public int push() throws Exception {
		return dbManger.execute((con) -> {
			PreparedStatement stm = con.prepareStatement("REPLACE INTO `distribution_cfg` (`key`, `value`) VALUES (?, ?)");

			for (Entry<String, Object> entry : properties.entrySet()) {
				stm.setString(1, entry.getKey());
				stm.setObject(2, entry.getValue(), Types.VARCHAR);

				stm.addBatch();
			}

			int[] executeResult = stm.executeBatch();

			int result = 0;
			for (int i : executeResult) {
				result += i;
			}

			return result;
		});
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if (dbManger == null) throw new IllegalArgumentException("DbManger is null");

		dbManger.execute((con) -> {
			Statement stm = con.createStatement();

			ResultSet result = stm.executeQuery("SELECT distribution_cfg.`key`, distribution_cfg.`value` FROM distribution_cfg");
			while (result.next()) {
				String key = result.getString("key");
				String value = result.getString("value");

				properties.put(key, value);
			}

			return null;
		});
	}

}
